#!/bin/bash
set -e

# 配置参数
PG_VERSION="15.6"
PG_SOURCE_DIR="/usr/local/src/postgresql-${PG_VERSION}"
PG_INSTALL_DIR="/usr/local/pgsql"
PG_DATA_DIR="/var/lib/pgsql/data"
PG_USER="postgres"
PROJ_VERSION="8.2.0"
PROJ_SOURCE_DIR="/usr/local/src/proj-${PROJ_VERSION}"
PG_TAR="postgresql-${PG_VERSION}.tar.gz"
POSTGIS_VERSION="3.4.3"
POSTGIS_TAR="postgis-${POSTGIS_VERSION}.tar.gz"
POSTGIS_SOURCE_DIR="/usr/local/src/postgis-${POSTGIS_VERSION}"

# 安装系统依赖（openEuler专用修正版）
echo "安装系统依赖..."
sudo yum install -y \
    gcc \
    gcc-c++ \
    make \
    cmake \
    readline-devel \
    zlib-devel \
    libxml2-devel \
    libxslt-devel \
    openssl-devel \
    systemd-devel \
    libicu-devel \
    geos-devel \
    json-c-devel \
    protobuf-c-devel \
    libtiff-devel \
    libpng-devel \
    libwebp-devel \
    wget \
    libuuid-devel \
    libcurl-devel \
    unzip

# 编译安装PROJ
echo "编译安装PROJ..."
sudo mkdir -p ${PROJ_SOURCE_DIR}
sudo tar -xzf proj-${PROJ_VERSION}.tar.gz -C ${PROJ_SOURCE_DIR} --strip-components 1

cd ${PROJ_SOURCE_DIR}
./configure --prefix=/usr/local/proj
make -j$(nproc)
sudo make install

# 确保系统能够找到新安装的PROJ库
sudo ldconfig

# 新增SQLite3依赖安装
echo "安装SQLite3开发包..."
sudo dnf install -y sqlite-devel

# 验证版本
SQLITE_VERSION=$(sqlite3 --version | awk '{print $1}')
if [[ "$SQLITE_VERSION" < "3.11" ]]; then
    echo "错误：SQLite3版本过低（当前：$SQLITE_VERSION），需要≥3.11"
    echo "请手动升级SQLite3：https://sqlite.org/download.html"
    exit 1
fi

# 创建postgres用户
if ! id "${PG_USER}" &>/dev/null; then
    echo "创建postgres用户..."
    sudo groupadd ${PG_USER}
    sudo useradd -g ${PG_USER} -s /bin/bash -d /home/${PG_USER} -m ${PG_USER}
fi

echo "检查PostgreSQL源码包..."
# 检查目标目录是否已有源码包
if [ ! -f "${PG_SOURCE_DIR}/${PG_TAR}" ]; then
    if [ -f "${PWD}/${PG_TAR}" ]; then
        echo "从当前目录复制源码包..."
        sudo cp -v "${PWD}/${PG_TAR}" "${PG_SOURCE_DIR}/"
    else
        echo "尝试自动下载源码包..."
        sudo mkdir -p "${PG_SOURCE_DIR}"
        cd "${PG_SOURCE_DIR}"
        sudo wget https://ftp.postgresql.org/pub/source/v${PG_VERSION}/postgresql-${PG_VERSION}.tar.gz
        cd - >/dev/null
    fi
fi

# 解压PostgreSQL源码
echo "解压PostgreSQL源码..."
sudo mkdir -p ${PG_SOURCE_DIR}
cd ${PG_SOURCE_DIR}  # 关键：先进入目标目录

# 验证压缩包完整性
if ! tar -tzf ${PG_TAR} >/dev/null 2>&1; then
    echo "错误：${PG_TAR} 文件损坏或格式不正确"
    exit 1
fi

sudo tar -xzf ${PG_TAR} --strip-components=1
echo "源码解压完成"

# 编译安装PostgreSQL（新增uuid支持）
echo "编译安装PostgreSQL..."
cd ${PG_SOURCE_DIR}
./configure --prefix=${PG_INSTALL_DIR} \
    --with-openssl \
    --with-libxml \
    --with-libxslt \
    --with-systemd \
    --with-uuid=e2fs
make -j$(nproc)
sudo make install

# 配置环境变量
echo "export PATH=${PG_INSTALL_DIR}/bin:\$PATH" | sudo tee /etc/profile.d/pgsql.sh
source /etc/profile.d/pgsql.sh

# 初始化数据库（新增日志配置）
echo "初始化数据库..."
sudo mkdir -p ${PG_DATA_DIR}
sudo chown -R ${PG_USER}:${PG_USER} ${PG_DATA_DIR}
sudo -u ${PG_USER} ${PG_INSTALL_DIR}/bin/initdb -D ${PG_DATA_DIR}

# 配置文件优化
sudo -u ${PG_USER} tee -a ${PG_DATA_DIR}/postgresql.conf <<EOF
listen_addresses = '*'
shared_buffers = 512MB
work_mem = 16MB
log_destination = 'stderr'
logging_collector = on
log_directory = 'log'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
log_rotation_age = 1d
EOF

# 配置systemd服务
echo "配置系统服务..."
sudo tee /etc/systemd/system/postgresql.service <<EOF
[Unit]
Description=PostgreSQL database server
After=network.target

[Service]
Type=notify
User=postgres
ExecStart=${PG_INSTALL_DIR}/bin/postgres -D ${PG_DATA_DIR}
ExecReload=/bin/kill -HUP \$MAINPID
KillMode=mixed
KillSignal=SIGINT
TimeoutSec=0

[Install]
WantedBy=multi-user.target
EOF

# 启动服务
echo "启动PostgreSQL服务..."
sudo systemctl daemon-reload
sudo systemctl enable postgresql
sudo systemctl start postgresql

# 安装PostGIS扩展
echo "检查PostGIS源码包..."
# 检查目标目录是否已有源码包
if [ ! -f "${POSTGIS_SOURCE_DIR}/${POSTGIS_TAR}" ]; then
    if [ -f "${PWD}/${POSTGIS_TAR}" ]; then
        echo "从当前目录复制PostGIS源码包..."
        sudo cp -v "${PWD}/${POSTGIS_TAR}" "${POSTGIS_SOURCE_DIR}/"
    else
        echo "尝试自动下载PostGIS源码包..."
        sudo mkdir -p "${POSTGIS_SOURCE_DIR}"
        cd "${POSTGIS_SOURCE_DIR}"
        sudo wget https://download.osgeo.org/postgis/source/${POSTGIS_TAR}
        cd - >/dev/null
    fi
fi

echo "编译安装PostGIS..."
sudo mkdir -p ${POSTGIS_SOURCE_DIR}
sudo tar -xzf ${POSTGIS_SOURCE_DIR}/${POSTGIS_TAR} -C ${POSTGIS_SOURCE_DIR} --strip-components 1
echo "源码解压完成"
cd ${POSTGIS_SOURCE_DIR}
./configure \
    --with-pgconfig=/usr/local/pgsql/bin/pg_config \
    --with-geos \
    --with-proj=/usr/local/proj \
    --with-gdal \
    --with-json \
    --with-protobuf \
    --with-raster \
    --with-topology \
    --without-sfcgal  # openEuler暂缺sfcgal依赖

make -j$(nproc)
sudo make install

# 创建扩展模板数据库（新增注释说明）
echo "创建模板数据库..."
sudo -u ${PG_USER} ${PG_INSTALL_DIR}/bin/createdb template_postgis
sudo -u ${PG_USER} ${PG_INSTALL_DIR}/bin/psql -d template_postgis <<EOF
-- 基础空间扩展
CREATE EXTENSION postgis;
-- 栅格数据支持
CREATE EXTENSION postgis_raster;
-- 拓扑支持
CREATE EXTENSION postgis_topology;
-- 模糊字符串匹配
CREATE EXTENSION fuzzystrmatch;
EOF

# 设置模板权限
sudo -u ${PG_USER} ${PG_INSTALL_DIR}/bin/psql -d postgres -c "UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template_postgis';"

# 最终验证
echo "验证安装..."
sudo -u ${PG_USER} ${PG_INSTALL_DIR}/bin/psql -c "SELECT version();"
sudo -u ${PG_USER} ${PG_INSTALL_DIR}/bin/psql -c "SELECT PostGIS_Full_Version();"

echo "安装成功完成！"
echo "重要路径信息："
echo "PostgreSQL程序目录：${PG_INSTALL_DIR}"
echo "数据库数据目录：${PG_DATA_DIR}"
echo "空间模板数据库：template_postgis"
echo "管理命令：sudo systemctl [start|stop|restart] postgresql"